package models;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.rmi.CORBA.Tie;

public class AnnounceManagement {
	private final String DRIVER = "org.postgresql.Driver";
	private final String URL = "jdbc:postgresql://localhost:5432/CourseRegistrationSystem";
	private final String SQL_USER = "postgres";
	private final String SQL_PASS = "dkmh";
	private String query;

	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;

	ArrayList<String> result = new ArrayList<>();

	public AnnounceManagement() throws SQLException, ClassNotFoundException {
		Class.forName(DRIVER);
		conn = DriverManager.getConnection(URL, SQL_USER, SQL_PASS);
	}

	public ArrayList<String> getContents() throws SQLException {
		String query = "SELECT noidung FROM thongbao ORDER BY ngaydang ASC";
		ps = conn.prepareStatement(query);
		rs = ps.executeQuery();
		while (rs.next())
			result.add(rs.getString("noidung"));
		return result;
	}

	public String getDate(String noidung) throws SQLException {
		String res = "";
		String query = "SELECT ngaydang FROM thongbao WHERE noidung='"
				+ noidung + "'";
		ps = conn.prepareStatement(query);
		rs = ps.executeQuery();
		while (rs.next())
			res = rs.getString("ngaydang");
		return res;
	}

	public void deleteAnn(String noidung) throws SQLException {
		String query = "DELETE FROM thongbao WHERE noidung=?";
		ps = conn.prepareStatement(query);
		ps.setString(1, noidung);
		ps.execute();
	}

	public void addAnn(String content) throws SQLException {
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		Date date = new Date();
		String currentDate = dateFormat.format(date);
		String query = "INSERT INTO thongbao VALUES(?,?)";
		ps = conn.prepareStatement(query);
		ps.setString(1, currentDate);
		ps.setString(2, content);
		ps.execute();

	}

	public static void main(String[] args) throws ClassNotFoundException,
			SQLException {
		AnnounceManagement am = new AnnounceManagement();
		am.addAnn("Hôm nay toàn trường sẽ được nghĩ học nàk");
	}
}
